'use strict';

const titbit = require('titbit');
const wxkey = require('./wxkey');
const gohttp = require('gohttp');
const mysql = require('mysql2/promise');

const app = new titbit({
    debug:true,
    https:true,
    key: 'fourgoldhua.cn.key',
    cert: 'fourgoldhua.cn.crt'
})

let token_key = '12312209857394659201222345679852';

let con = mysql.createPool({
  host:'154.8.156.240',
  port:'2020',
  user:'root',
  password:'Ljj0222.',
  database:'tuijian'
});


app.post('/wxgetId',async c => {

    let login_url = `https://api.weixin.qq.com/sns/jscode2session`
                    + `?appid=${wxkey.appid}`
                    + `&secret=${wxkey.secret}`
                    + `&js_code=${c.body.code}`
                    + `&grant_type=authorization_code`;
    console.log(c.body.code);
    
    let result = await gohttp.get(login_url);
    c.res.body = result.text();
    let r = result.json();
    if(r.openid === undefined){
      c.status(500)
      return;
    }
    
    //加密openid和session_key数据
    let info = {
            openid: r.openid,
            //expires: 7200000,
            session:r.session_key,
            //timestamp: Date.now(),
            random: Math.random()
    }

    //console.log(info.openid,r.session_key);
    let token = c.helper.aesEncrypt(JSON.stringify(info),token_key);
    //console.log(token);
    c.res.body = info.openid;
})

app.post('/aes-test/:data',async c => {
    //let data1 = c.helper.aesDecrypt(c.param.data,token_key);
    let data2 = c.param.data;
    //console.log('c:    ',c);
    //console.log('data2:   ',data2);
    //let session = c.param.data;
    //console.log(c.body);
    let opnid = data2;//用户id
    let name = c.body.username;//用户名
    let img = c.body.avatarUrl;//用户头像
    
    async function getAreas(){
      const sql = `select * from user_table where id = '${opnid}'`;
      let [rows] = await con.execute(sql);
      return rows;
    }
    let arr = await getAreas();
    console.log(arr);
    //如果没有则插入数据
    //接下来还有一步，是将用用户的头像和姓名一起插入
    if(arr.length == 0){
      const sql1 = `INSERT INTO user_table(id,user_name,user_img) VALUES('${opnid}','${name}','${img}')`;
      let [rows] = await con.execute(sql1);
      console.log('插入成功');
    }

})

app.run(3003);
